﻿using System;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Infrastructure;

namespace Xoohoo.ActionFilters.Authorization
{
    public class AdvancedAuthorizationFilter : IAuthorizationFilter
    {
        private readonly IDependencyResolver _dependencyResolver;
        private readonly Func<IUser, bool> _checkUser;

        public AdvancedAuthorizationFilter(Func<IUser, bool> checkUser) 
            : this(DependencyResolver.Current,checkUser) { }

        public AdvancedAuthorizationFilter(IDependencyResolver dependencyResolver, Func<IUser, bool> checkUser)
        {
            if (dependencyResolver == null)
                throw new ArgumentNullException("dependencyResolver");
            if (checkUser == null)
                throw new ArgumentNullException("checkUser");

            this._dependencyResolver = dependencyResolver;
            this._checkUser = checkUser;
        }

        #region IAuthorizationFilter Members

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //当前用户
            IUser user = _dependencyResolver.GetService<IUser>();

            // 如果用户尚未登录，或者没有通过验证
            if (user == null || !user.IsAuthenticated || !_checkUser(user))
            {
                //当前模块的认证模块
                IAuthenticationModule authenticationModule = _dependencyResolver.GetService<IAuthenticationModule>();
                if (authenticationModule == null)
                    throw new System.Exception("AuthenticationModule of current module is null.");
                string signInUrl = authenticationModule.GetSignInUrl(filterContext.RequestContext);
                filterContext.SetActionResult(signInUrl);
            }

        }

        #endregion
    }
}
